﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using ServiceBus.Contract;

namespace ServiceBus.EndPoint
{
    public class FunctionServiceConnector
    {

        private static List<ProxyStructure> FunctionServiceClients = new List<ProxyStructure>();
        private static T OpenService<T>(ProxyStructure proxy)
        {
            try
            {
                if (proxy.RegisterProxy == null // || (DateTime.Now - proxy.RegisterTime).Minutes > 1
                        || proxy.RegisterProxy.State == CommunicationState.Faulted)
                {
                    System.ServiceModel.Channels.Binding bind = new NetTcpBinding();
                    EndpointAddress address = new EndpointAddress(proxy.RegisterPath);

                    proxy.RegisterTime = DateTime.Now;
                    proxy.RegisterProxy = new ServiceProxy(bind, address);
                    proxy.RegisterProxy.Open();
                }
                return (T)((IStandardService)proxy.RegisterProxy);
            }
            catch { return default(T); }
        }
        private static ServiceProxy[] FunctionServiceList
        {
            get
            {
                return FunctionServiceClients.Select(p => p.RegisterProxy).ToArray();
            }
        }

        public static T CreateFunctionService<T>(string name, string path) where T : IStandardService
        {
            ProxyStructure client = FunctionServiceClients.FirstOrDefault(s => s.Name == name.ToUpper().Trim());
            if (client == null)
            {
                client = new ProxyStructure() { RegisterPath = path + "Function", Name = name.ToUpper().Trim() };
                FunctionServiceClients.Add(client);
            }
            return OpenService<T>(client);
        }
        public static T GetFunctionService<T>(string name) where T : IStandardService
        {
            ProxyStructure client = FunctionServiceClients.FirstOrDefault(s => s.Name == name.ToUpper().Trim());
            if (client == null) return default(T);
            return OpenService<T>(client);
        }
        public static void AddKnownType(Type type)
        {
            ServiceBus.Contract.KnowTypes.AddKnownType(type);
        }
        public static void CloseFunctionService(string servicename)
        {
            ProxyStructure client = FunctionServiceClients.FirstOrDefault(s => s.Name == servicename.ToUpper().Trim());
            ServiceProxy service = client.RegisterProxy;
            if (service != null)
            {
                try
                {
                    service.Abort();
                }
                catch { }
                finally
                {
                    FunctionServiceClients.Remove(client);
                }
            }
        }
                
    }
}
